document.addEventListener('DOMContentLoaded', () => {
    const firstLineInput = document.getElementById('first-line');
    const styleSelect = document.getElementById('style');
    const generateBtn = document.getElementById('generate-btn');
    const randomBtn = document.getElementById('random-btn');
    const displayFirst = document.getElementById('display-first');
    const displaySecond = document.getElementById('display-second');

    // 生成下联
    generateBtn.addEventListener('click', async () => {
        const firstLine = firstLineInput.value.trim();
        const style = styleSelect.value;

        if (!firstLine) {
            alert('请输入上联');
            return;
        }

        try {
            const response = await fetch('/api/generate_couplet', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    first_line: firstLine,
                    style: style
                })
            });

            const result = await response.json();

            if (result.error) {
                throw new Error(result.error);
            }

            displayFirst.textContent = result.first;
            displaySecond.textContent = result.second;
        } catch (error) {
            alert('生成失败: ' + error.message);
            console.error(error);
        }
    });

    // 随机对联
    randomBtn.addEventListener('click', async () => {
        const style = styleSelect.value;

        try {
            const response = await fetch('/api/random_couplet', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    style: style
                })
            });

            const result = await response.json();

            if (result.error) {
                throw new Error(result.error);
            }

            firstLineInput.value = result.first;
            displayFirst.textContent = result.first;
            displaySecond.textContent = result.second;
        } catch (error) {
            alert('获取随机对联失败: ' + error.message);
            console.error(error);
        }
    });

    // 复制对联
    function copyCouplet() {
        const firstLine = document.getElementById('display-first').textContent;
        const secondLine = document.getElementById('display-second').textContent;
        const couplet = `${firstLine}\n${secondLine}`;
        
        navigator.clipboard.writeText(couplet)
            .then(() => {
                alert('对联已复制到剪贴板');
            })
            .catch(() => {
                alert('复制失败，请手动复制');
            });
    }

    // 保存对联
    function saveCouplet() {
        const firstLine = document.getElementById('display-first').textContent;
        const secondLine = document.getElementById('display-second').textContent;
        const style = document.getElementById('style-select').value;
        
        fetch('/api/save_couplet', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                first_line: firstLine,
                second_line: secondLine,
                style: style
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                alert('对联保存成功');
            } else {
                throw new Error(data.message || '保存失败');
            }
        })
        .catch(error => {
            alert('保存失败: ' + error.message);
            console.error(error);
        });
    }

    // 初始化事件监听器
    function initEventListeners() {
        document.getElementById('generate-btn').addEventListener('click', generateCouplet);
        document.getElementById('random-btn').addEventListener('click', getRandomCouplet);
        document.getElementById('copy-btn').addEventListener('click', copyCouplet);
        document.getElementById('save-btn').addEventListener('click', saveCouplet);
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', initEventListeners);

});